package com.cn.shuangzi.ad.custom;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.mediation.MediationConstant;
import com.bytedance.sdk.openadsdk.mediation.bridge.custom.splash.MediationCustomSplashLoader;
import com.bytedance.sdk.openadsdk.mediation.custom.MediationCustomServiceConfig;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.bean.KsErrorInfo;
import com.cn.shuangzi.ad.bean.YlhErrorInfo;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.ADUtil;
import com.cn.shuangzi.ad.util.ThreadUtils;
import com.cn.shuangzi.util.SZUtil;
import com.kwad.sdk.api.KsAdSDK;
import com.kwad.sdk.api.KsLoadManager;
import com.kwad.sdk.api.KsScene;
import com.kwad.sdk.api.KsSplashScreenAd;
import com.kwad.sdk.api.model.AdExposureFailedReason;
import com.kwad.sdk.api.model.AdExposureFailureCode;
import com.kwad.sdk.api.model.AdnType;
import com.qq.e.comm.constants.BiddingLossReason;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import androidx.annotation.Nullable;

public class KsCustomerSplash extends MediationCustomSplashLoader {
    private KsSplashScreenAd mSplashAd;
    private Context mContext;

    private int price;

    @Override
    public void load(final Context context, AdSlot adSlot, final MediationCustomServiceConfig serviceConfig) {
        /**
         * 在子线程中进行广告加载
         */
        ThreadUtils.runOnThreadPool(new Runnable() {
            @Override
            public void run() {
                mContext = context;
                if (KsAdSDK.getLoadManager() != null) {
                    long posId;
                    try {
                        posId = Long.parseLong(serviceConfig.getADNNetworkSlotId()); //广告位id
                    } catch (Exception e) {
                        callLoadFail(ADConst.AD_ERROR, "代码位ID不合法");
                        return;
                    }
                    KsScene scene = new KsScene.Builder(posId).build();
                    KsAdSDK.getLoadManager().loadSplashScreenAd(scene, new KsLoadManager.SplashScreenAdListener() {
                        @Override
                        public void onError(int i, String s) {
                            ADUtil.logError("快手开屏加载失败 errCode:" + i + "  errMsg:" + s);
                            ADManager.getInstance().setSplashKsErrorInfo(new KsErrorInfo(AdExposureFailureCode.OTHER));
                            callLoadFail(i, s);
                        }

                        @Override
                        public void onRequestResult(int i) {

                        }

                        @Override
                        public void onSplashScreenAdLoad(@Nullable KsSplashScreenAd ksSplashScreenAd) {
                            if (ksSplashScreenAd != null) {
                                mSplashAd = ksSplashScreenAd;
                                ADManager.getInstance().setKsSplashAd(mSplashAd);
                                if (isClientBidding()) {
                                    double ecpm = ksSplashScreenAd.getECPM();
                                    if (ecpm < 0) {
                                        ecpm = 0;
                                    }
                                    price = (int) ecpm;
                                    ADUtil.logError("快手开屏加载成功 ecpm:" + ecpm);
                                    ADManager.getInstance().setSplashKsErrorInfo(new KsErrorInfo(new AdExposureFailedReason().setAdnType(AdnType.THIRD_PARTY_AD)));
                                    callLoadSuccess(ecpm);
                                } else {
                                    callLoadSuccess();
                                }
                            }else{
                                ADManager.getInstance().setSplashKsErrorInfo(new KsErrorInfo(AdExposureFailureCode.OTHER));
                            }
                        }
                    });
                }
            }
        });
    }

    @Override
    public void showAd(final ViewGroup container) {

        if (mSplashAd!=null&&price > 0) {
            mSplashAd.setBidEcpm(price,price-80);
            ADUtil.logError("=======上报快手开屏数据======="+price);
        }
        ADUtil.logError("=======显示 快手 开屏=======");
        /**
         * 先切子线程，再在子线程中切主线程进行广告展示
         */
        ThreadUtils.runOnUIThreadByThreadPool(new Runnable() {
            @Override
            public void run() {
                if (mSplashAd != null && container != null) {
                    Context context = mContext == null ? mContext : mContext.getApplicationContext();
                    View view = mSplashAd.getView(context, new KsSplashScreenAd.SplashScreenAdInteractionListener() {
                        @Override
                        public void onAdClicked() {
                            ADUtil.logError("快手开屏 onAdClicked");
                            callSplashAdClicked();
                        }

                        @Override
                        public void onAdShowError(int i, String s) {
                            ADUtil.logError("快手开屏 onAdShowError ：Code"+i+"，Msg："+s);
                        }

                        @Override
                        public void onAdShowEnd() {
                            ADUtil.logError("快手开屏 onAdShowEnd");
                            callSplashAdDismiss();
                        }

                        @Override
                        public void onAdShowStart() {
                            ADUtil.logError("快手开屏 onAdShowStart");
                            callSplashAdShow();
                        }

                        @Override
                        public void onSkippedAd() {
                            ADUtil.logError("快手开屏 onSkippedAd");
                            callSplashAdSkip();
                        }

                        @Override
                        public void onDownloadTipsDialogShow() {

                        }

                        @Override
                        public void onDownloadTipsDialogDismiss() {

                        }

                        @Override
                        public void onDownloadTipsDialogCancel() {

                        }
                    });
                    if (view != null) {
                        ViewParent parent = view.getParent();
                        if (parent instanceof ViewGroup) {
                            ((ViewGroup) parent).removeView(view);
                        }
                        view.setLayoutParams(new
                                ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.MATCH_PARENT));
                        container.removeAllViews();
                        container.addView(view);
                    }
                }
            }
        });
    }

    @Override
    public MediationConstant.AdIsReadyStatus isReadyCondition() {
        /**
         * 在子线程中进行广告是否可用的判断
         */
        Future<MediationConstant.AdIsReadyStatus> future = ThreadUtils.runOnThreadPool(new Callable<MediationConstant.AdIsReadyStatus>() {
            @Override
            public MediationConstant.AdIsReadyStatus call() throws Exception {
                if (mSplashAd != null && mSplashAd.isAdEnable()) {
                    return MediationConstant.AdIsReadyStatus.AD_IS_READY;
                } else {
                    return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
                }
            }
        });
        try {
            MediationConstant.AdIsReadyStatus result = future.get(500, TimeUnit.MILLISECONDS);//设置500毫秒的总超时，避免线程阻塞
            if (result != null) {
                return result;
            } else {
                return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
    }

    /**
     * 是否clientBidding广告
     *
     * @return
     */
    public boolean isClientBidding() {
        return getBiddingType() == MediationConstant.AD_TYPE_CLIENT_BIDING;
    }

    /**
     * 是否serverBidding广告
     *
     * @return
     */
    public boolean isServerBidding() {
        return getBiddingType() == MediationConstant.AD_TYPE_SERVER_BIDING;
    }


}
